﻿using Doolin.MongoRepository.Commons;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Doolin.MongoRepository
{
  public class MongoContext : IMongoDbContext
  {
    private readonly List<Func<Task>> _commands;
    private readonly IMongoClient _client;
    private readonly IMongoDatabase _database;

    public MongoContext(string connectionString, string dbName)
    {
      BsonDefaults.GuidRepresentation = GuidRepresentation.CSharpLegacy;
      _commands = new List<Func<Task>>();
      RegisterConventions();

      _client = new MongoClient(connectionString);
      _database = _client.GetDatabase(dbName);
    }
    private void RegisterConventions()
    {
      var pack = new ConventionPack
        {
            new IgnoreExtraElementsConvention(true),
            new IgnoreIfDefaultConvention(true)
        };
      ConventionRegistry.Register("My Solution Conventions", pack, t => true);
    }
    public int SaveChanges()
    {
      var qtd = _commands.Count;
      foreach (var command in _commands)
      {
        command();
      }

      _commands.Clear();
      return qtd;
    }
    public IMongoCollection<T> GetCollection<T>(string name)
    {
      return _database.GetCollection<T>(name);
    }
    public void Dispose()
    {
      GC.SuppressFinalize(this);
    }
    public Task AddCommand(Func<Task> func)
    {
      _commands.Add(func);
      return Task.CompletedTask;
    }
    public IMongoCollection<T> GetCollection<T>()
    {
      return _database.GetCollection<T>(typeof(T).Name);

    }
    public IMongoCollection<BsonDocument> GetBsonMongoCollection(string collectionName)
    {
      return _database.GetCollection<BsonDocument>(collectionName);
    }
  }
}
